<template>
  <!-- 目录管理 -->
  <div class='container'>
    <div class="app-container">
      <el-card shadow="never">
        <!-- 搜索 -->
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="目录名称">
            <el-input v-model="formInline.user" placeholder="请输入目录名称"></el-input>
          </el-form-item>
          <el-form-item label="状态" class="new-font">
            <el-select v-model="formInline.region" placeholder="请选择" class="new-fontsize">
              <el-option label="启用" value="shanghai"></el-option>
              <el-option label="禁用" value="beijing"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="search-formitem">
            <el-button @click="clear">清除</el-button>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
          </el-form-item>
          <el-form-item class="new-formitem">
            <el-button type="success" @click="ShowAddBox('add')" class="new-button">新增目录</el-button>
          </el-form-item>
        </el-form>
        <el-alert v-if="alertText !== ''" :title="alertText" type="info" class="alert" :closable="false" show-icon></el-alert>
        <!-- 表格 -->
        <el-table :data="list" element-loading-text="给我一点时间" fit highlight-current-row style="width: 100%;">
          <el-table-column type="index" :index="handleIndex" label="序号" width="100">
          </el-table-column>
          <el-table-column prop="subjectName" label="所属学科" width="180">
          </el-table-column>
          <el-table-column prop="directoryName" label="目录名称" width="180">
          </el-table-column>
          <el-table-column prop="username" label="创建者" width="180">
          </el-table-column>
          <el-table-column prop="addDate" label="创建日期" width="180">
          </el-table-column>
          <el-table-column prop="totals" label="面试题数量" width="180">
          </el-table-column>
          <el-table-column prop="state" label="状态" width="180" class="filter-item">
            <template #default="{row}">已{{isOk(row.state)}}</template>
          </el-table-column>

          <el-table-column label=" 操作" class="new-buttext">
            <template v-slot="{row}">
              <el-button style="font-size: 14px;" type="text" @click="handlestart(row)">{{row.state ? "禁用":"启用"}}</el-button>
              <el-button style="font-size: 14px;" type="text" :disabled="row.state ? true : false " @click="handleEdit(row)">修改</el-button>
              <el-button style="font-size: 14px;" type="text" :disabled="row.state ? true : false " @click="handleDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination :page-sizes="[10, 20, 30, 40, 50, 100]" layout="->,prev, pager,next,sizes,jumper,  total" :total="total" :current-page="queryParams.page" :page-size="queryParams.pages" @current-change="changePage" @size-change="sizeChange" />

        <!-- 新增目录弹层 -->
        <el-dialog id="dialog" :title="title" width="430px" :visible.sync="isShowAddBox" class="new-content-lqy">
          <el-form ref="roleForm" :model="form" :rules="rules" class="new-content-l">
            <el-form-item label="所属学科" prop="subjectID">
              <el-select v-model="form.subjectID" style="width:300px" placeholder="请选择">
                <!-- <el-option label="请选择学科" :value="form.name" /> -->
                <el-option v-for="(item,index) in selectList" :key="index" :label="item.subjectName" :value="item.subjectID" />
              </el-select>
            </el-form-item>
            <el-form-item label="目录名称" prop="directoryName" :value="form.directoryName">
              <el-input v-model="form.directoryName" placeholder="请输入目录名称" style="width:300px" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="btnCancel">取消</el-button>
            <el-button type="primary" @click="handleAdd">确认</el-button>
          </template>
        </el-dialog>

        <!-- 新增标签弹层 -->
        <!-- <ArticlesAdd :show-dialog.sync="showDialog" :edit-item="editItem" :flag="flag" /> -->
      </el-card>
    </div>
  </div>
</template>

<script>
// simple目录简单列表，
import { status } from '@/api/hmmm/constants.js'
import { add, list, remove, changeState, update, detail } from '@/api/hmmm/directorys.js'
// import ArticlesAdd from './../components/directorys-add.vue'
export default {
  name: 'subjects-directorys',
  components: {},
  data () {
    return {
      // 添加弹窗标志位
      isShowAddBox: false,
      // 弹窗列表
      permissions: [],
      // 添加表单数据
      form: {
        id: '',
        subjectID: '',
        directoryName: ''
      },
      selectList: [],
      rules: {
        subject: [
          { required: true, message: '请选择学科', trigger: ['blur', 'change'] }
        ],
        description: [
          { required: true, message: '请输入目录名称', trigger: ['blur', 'change'] }
        ]
      },
      total: 0, // 总条数
      list: [], // 列表
      // 查询参数
      queryParams: {
        page: 1, // 当前页数
        pagesize: 10 // 总页数
      },
      alertText: '',
      items: [{
        id: '', // 序号
        subjectName: '', // 所属学科*
        directoryName: '', // 目录名称*
        username: '', // 创建者*
        addDate: '', // 创建日期*
        totals: '', // 面试题数量*
        state: '' // 状态*
      }],
      formInline: {
        user: '', // 目录名称
        region: '' // 状态
      }
    }
  },
  computed: {
    title () {
      return this.form.id === '' ? '添加目录' : '修改目录'
    }
  },
  methods: {
    // 状态
    isOk (type) {
      const getstate = status.find(item => parseInt(item.value) === parseInt(type))
      if (getstate) {
        return getstate.label
      } else {
        this.status = '其他'
      }
    },
    // 监听每页条数的变化
    sizeChange (pagesize) {
      this.queryParams.pagesize = pagesize
      this.loadlist()
    },
    // 监听页码的切换操作
    changePage (page) {
      // page表示切换后最新的页码
      this.queryParams.page = page
      this.loadlist()
    },
    // 启用
    async handlestart (row) {
      // 将state值反转(如果state为1时取0，反之取1)
      row.state = row.state === 0 ? 1 : 0
      const res = await changeState(row)
      if (res.status === 200) {
        this.loadlist()
        this.$message.success('操作成功')
      }
    },
    // 修改
    async handleEdit (row) {
      const ret = await detail(row)
      this.form = ret.data
      this.isShowAddBox = true
    },
    // 根据目录id删除
    async handleDelete (id) {
      try {
        const ret = await this.$confirm('确认要删除该目录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // 点击了取消操作
        if (ret === 'cancel') return
        // 点击了确定操作，调用接口
        const delRet = await remove({ id })
        if (delRet.status === 200) {
          // 删除成功，刷新列表
          this.loadlist()
          this.$message.success('删除目录成功')
        } else {
          // 删除失败
          this.$message.error(delRet.message)
        }
      } catch {
        this.$message.error('删除目录失败')
      }
    },
    // 清除
    clear () {
      this.formInline.user = ''
      this.formInline.region = ''
    },
    // 搜索 queryParams
    onSubmit () {
      this.queryParams.page = 1
      this.loadlist(this.queryParams)
    },
    // 动态生成索引
    handleIndex (index) {
      const { page, pagesize } = this.queryParams
      return (page - 1) * pagesize + index + 1
    },
    // 获取列表数据
    async loadlist () {
      try {
        const ret = await list(this.queryParams)
        // console.log(ret)
        this.list = ret.data.items

        this.total = ret.data.counts
        this.alertText = `共${this.total}条记录`
      } catch {
        this.$message.error('获取目录列表失败')
      }
    },
    // 取消关闭弹窗
    btnCancel () {
      this.isShowAddBox = false
      this.form = {
        id: '',
        subjectID: '',
        directoryName: ''
      }
      this.$refs.roleForm.resetFields()
    },
    // 新增按钮
    async ShowAddBox () {
      this.isShowAddBox = true
      const ret = await list()
      this.selectList = ret.data.items
    },
    // 新增提交表单
    handleAdd () {
      this.$refs.roleForm.validate(async valid => {
        if (!valid) return
        // debugger
        // 验证通过
        try {
          // 添加
          if (!this.form.id) {
            const ret = await add(this.form)
            // console.log(ret)
            if (ret.status === 200) {
              // 添加成功：关闭弹窗，刷新列表，清空表单
              this.$refs.roleForm.resetFields()
              this.isShowAddBox = false
              this.form = this.$options.data().form
              this.loadlist()
              this.$message.success('添加目录成功')
            }
          } else {
            const ret = await update(this.form)
            if (ret) {
              this.$refs.roleForm.resetFields()
              this.form = {
                id: '',
                subjectID: '',
                directoryName: ''
              }
              this.isShowAddBox = false
              this.loadlist()
            }
          }
        } catch {
          this.$message.error('添加目录失败')
        }
      })
    }
  },
  created () {
    this.loadlist()
  }
}

</script>

<style scoped lang="scss">
.new-buttext {
  font-size: 16px;
}
.demo-form-inline {
  display: flex;
  margin: 0;
}
.app-container .new-content-lqy .new-content-l {
  margin: 0;
}
// .el-dialog__footer {
//   text-align: right !important;
// }
.el-button--medium {
  font-size: 12px;
}
.new-formitem {
  display: flex;
  flex: 1;
  justify-content: flex-end;
}
.new-font {
  font-size: 20px;
}
</style>
